import { defineStore } from 'pinia';
import { getRightData } from '@/api/earlyWarning';
import { onMounted } from 'vue';
import { AlarmType } from '@/constants/components/alarmType';
import { mapBackendData, type moduleInfo } from '@/utils/mapBackendData';
import { getAlarmInfo } from '@/api/deviceAlarms';
import { getAlarmTypeCode } from '@/enums/AlarmTypeEnum';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import COMPONENT_TITLES from '@/constants/components/componentsTitle';
import { useDialogStore } from '@/store/modules/useDialogStore';

interface IAlarmInfos {
  total: number;
  potencyAlarmNum: number;
  pressureAlarmNum: number;
  flowAlarmNum: number;
  normallyOpenAlarmNum: number;
  thirdAlarmNum: number;
  echartsData: any;
}

const ALARM_TYPE = {
  '浓度报警': { countKey: 'potencyAlarmNum', dataKey: 'echartsData' },
  '压力报警': { countKey: 'pressureAlarmNum', dataKey: 'echartsData' },
  '阀门状态报警': { countKey: 'normallyOpenAlarmNum', dataKey: 'echartsData' },
  '破坏报警': { countKey: 'thirdAlarmNum', dataKey: 'echartsData' }
};
export const useAlarmTypeStore = defineStore('alarmType', () => {
  const alarmType = ref(<IAlarmInfos>{});
  const alarmList = ref<moduleInfo[]>(AlarmType);
  const { addPoint, clearAllPoints } = useCesiumPoints();
  const currentName = ref(''); //用来控制折叠框点击之后展开对应的item
  const dataSource = reactive<Record<string, any[]>>({});
  const { openDialog } = useDialogStore();
  const { flyTo } = useDialogStore();

  // 清除报警点公共逻辑
  const clearAlarmPoints = (name: string): boolean => {
    if (dataSource[name]) {
      clearAllPoints(dataSource[name]);
      alarmList.value.find((itm) => itm.name === name).clickStatus = false;
      delete dataSource[name];
      return false;
    }
    return true;
  };
  // 设置报警状态和点位的公共逻辑
  const setAlarmPoints = (data, name) => {
    openDialog('alarmTypeModule');
    flyTo({ longitude: 117.140035075, latitude: 36.798747059 }, 400000);
    currentName.value = name;
    alarmList.value.find((itm) => itm.name === name).clickStatus = true;
    dataSource[name] = data.map((point) => addPoint(point, name, COMPONENT_TITLES.ALARM_TYPE));
  };
  //告警类型饼图的点击事件
  const alarmsTypeHandle = async (item) => {
    try {
      if (clearAlarmPoints(item.name)) {
        const { data } = await getAlarmInfo({
          type: getAlarmTypeCode(item.name),
          effective: item.data.effective
        });
        setAlarmPoints(data, item.name);
      }
    } catch (error) {
      console.log(error);
    }
  };
  //点击下面的卡片的事件
  const alarmsTypeCardHandle = async (item: any, name: string) => {
    console.log(item);
    try {
      if (clearAlarmPoints(name)) {
        const data = item.list?.find((itm) => itm.name === name) || [];
        if (!data.clickData && data.clickData.length == 0) return;
        // 点击之后，修改点击状态
        setAlarmPoints(data.clickData, name);
      }
    } catch (error) {
      console.log(error);
    }
  };
  const initClearPoints = () => {
    Object.keys(dataSource).forEach((key) => {
      clearAllPoints(dataSource[key]);
      delete dataSource[key];
    });
    alarmList.value.forEach((item) => {
      item.clickStatus = false;
    });
  };
  onMounted(async () => {
    const { data } = await getRightData({ type: 'alarmStatistics' });
    alarmType.value = data.alarmStatistics;
    // 创建名称到项的映射
    const alarmMap = new Map(alarmList.value.map((itm) => [itm.name, itm]));

    data.alarmStatistics.echartsData.forEach((item) => {
      const matchedItem = alarmMap.get(item.name);
      if (matchedItem) {
        matchedItem.list.push(item); // 将item添加到数组
        matchedItem.value = item.value;
      }
    });
  });
  return {
    alarmType,
    alarmList,
    currentName,
    alarmsTypeHandle,
    initClearPoints,
    alarmsTypeCardHandle
  };
});
